package machine.utils;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 缓存
 *
 * @author zhanghui145
 * @date 2021/12/31 14:56
 * @since 1.0.0
 */
@Component
public class CacheUtils {

    private static Map<String, Value> cacheMap = new ConcurrentHashMap<>();

    public void put(String id) {
        Value value = new Value();
        value.setDate(new Date());
        cacheMap.put(id, value);
    }

    public void remove(String id) {
        cacheMap.remove(id);
    }

    public boolean contain(String id){
        return cacheMap.containsKey(id);
    }

    public void expireClear(){
        final Date now = new Date();
        for (Map.Entry<String, Value> entry : cacheMap.entrySet()) {
            Value v = entry.getValue();
            long dValue = DateUtil.between(v.getDate(), now , DateUnit.SECOND);
            if (dValue > 300L) {
                cacheMap.remove(entry.getKey());
            }
        }
    }
    @Data
    private static class Value {
        private Date date;
    }
}
